package com.wlyuan.open.scanner.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author lijing
 * @description
 */
@Configuration
@MapperScan(basePackages = {"com.wlyuan.open.scanner.dao.write"}, sqlSessionFactoryRef = "WriteFactory")
@Slf4j
public class ScannerWriteDaoConfiguration {

    /**
     * 封装数据源对象创建, 该方法就已经将数据源的各个数据封装到该对象中
     *
     * @return
     */
    @Bean(name = "WriteDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource wlyDataSource() {
        return new DruidDataSource();
    }

    /**
     * SqlSession对象创建
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "WriteFactory")
    public SqlSessionFactory wlyFactory(@Qualifier("WriteDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.wlyuan.open.scanner.dao.entity");
        bean.setDataSource(dataSource);
        bean.setPlugins(mybatisPlusInterceptorWrite());
        return bean.getObject();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptorWrite() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 方言
        paginationInnerInterceptor.setDbType(DbType.SQL_SERVER);
        paginationInnerInterceptor.setMaxLimit(1000L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

    @Bean(name = "writeSqlSessionTemplate")
    public SqlSessionTemplate mssqlSqlSessionTemplate(
            @Qualifier("WriteFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
